import React from 'react';
import {
  StyleSheet,
  Image,
  SafeAreaView,
} from 'react-native';
import { iconWayOrderCoffee, iconWayOrderGray, empty01 } from '@/images';
import { XMListView, msg, XMHeader, XMEmpty } from '@/common';
import {
  mainBgColorLightGray,
  fontColorBlack,
  fontColorLightGray,
  px2dp,
} from '@/styles';
import { HeadTabs } from '@/components';
import api from '@/api';
import WayOrderItem from './components/way-order-item';
import { screenWidth } from '../../../common/styles';

export default class WayOrder extends React.Component {
  static navigationOptions = () => ({
    title: '运单',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconWayOrderCoffee : iconWayOrderGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      status: -1,
      unitList: [],
      orderList: [],
      modalVisible: false,
      transparent: true,
      previewAdress: '',
    };
    this.myList = null;
  }

  changeStatus = (status) => {
    this.setState({ status });
  };

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;

    this.getUnitList();
  }

  componentWillUnmount() {}

  render() {
    const tabSources = [
      {
        tab: '全部',
        type: -1,
      },
      {
        tab: '未完成',
        type: 1,
      },
      {
        tab: '已完成',
        type: 2,
      },
    ];
    const { status } =
      this.state;

    return (
      <SafeAreaView style={styles.container}>
        <XMHeader
          style={{ borderBottomWidth: 0 }}
          title='我的运单'
          renderLeft={() => {
            return null;
          }}
        />
        <HeadTabs
          tabSources={tabSources}
          changeStatus={(type) => this.changeStatus(type)}
          status={status}
        />

        <XMListView
          url='supply-app-api/api/v1/supply/driver/pageDriverWaybill'
          methods='GET'
          params={{ status }}
          dataPropsName='data.list'
          renderRow={(item, index) => this._renderItem(item, index)}
          renderEmpty={() => <XMEmpty emptyImg={empty01} desc='您暂时没有该类运单噢~' boxStyle={{ marginTop: px2dp(200) }} />}
          onRefresh={() => {
            this.confirmDriver();
          }}
        />
      </SafeAreaView>
    );
  }

  _renderItem = (item, index) => {
    const { unitList } = this.state;
    return (
      <WayOrderItem
        detail={item}
        key={index}
        unitList={unitList}
        handerClick={this.handerClick}
        toReceipt={this.toReceipt}
      />
    );
  };

  handerClick = (data) => {
    msg.emit('router: goToNext', {
      routeName: 'DriverOrderDetail',
      businessNo: data.transportNo,
      plat: 3, // 1  货主端   2车主端  3 司机端
      routerFrom: 'DriverWayOrder',
    });
  };

  toReceipt = (item) => {
    if (item.transportStatus === 1) {
      api.supply.getUploadTick({ transportNo: item.transportNo }).then((res) => {
        if (res.data.needReceipt === 2) {
          this.submitUploadTick(item, res.data);
        } else {
          msg.emit('router: goToNext', {
            routeName: 'ReceiptUpload',
            routerFrom: 'DriverWayOrder',
            data: item,
            transportNo: item.transportNo,
            guideData: res.data,
          });
        }
      });
    } else {
      msg.emit('router: goToNext', {
        routeName: 'ReceiptEdit',
        routerFrom: 'DriverWayOrder',
        transportNo: item.transportNo,
      });
    }
  };

  // 获取单位
  getUnitList = () => {
    return new Promise((resolve) => {
      api.supply.unitList().then((res) => {
        this.setState({ unitList: res.data }, () => {
          resolve(res);
        });
      });
    });
  };

  // 提交数据api //上传发货单，收货单
  submitUploadTick = (item, guideData) => {
    // 拼接参数
    let params = {
      id: guideData.id,
      transportNo: item.transportNo,
      details: [],
    };
    api.supply.uploadTick(params).then((res) => {
      if (res.success) {
        msg.emit('app:tip', { text: '提交成功' });
        this._onRefresh();
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 全部确认订单
  confirmDriver = () => {
    api.supply.autoCheckTransports().then((res) => {
      if (res.success) {
        // msg.emit('router: refreshRoute', {
        //   routeName: 'DriverTab',
        // });
      } else {
        msg.emit('app:tip', { text: '遇到网络错误，请重试' });
      }
    });
  };

  // 刷新
  _onRefresh = () => {
    this.myList._init();
  };
}

const styles = StyleSheet.create({
  container: {
    width: screenWidth,
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
  },
  mainCon: {
    backgroundColor: '#F5F5F5',
    padding: px2dp(24),
    borderRadius: px2dp(6),
  },
  bot: {
    height: px2dp(34),
    width: '100%',
  },
  title: {
    fontSize: px2dp(32),
    fontWeight: 'bold',
    color: fontColorBlack,
    marginLeft: px2dp(14),
    flex: 1,
  },
  line: {
    marginHorizontal: px2dp(16),
    color: fontColorLightGray,
  },
  name: {
    paddingHorizontal: px2dp(12),
    paddingVertical: px2dp(16),
    backgroundColor: mainBgColorLightGray,
    flexDirection: 'row',
    alignItems: 'center',
  },
  driver: {
    width: px2dp(32),
    height: px2dp(32),
  },
  user: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: px2dp(24),
  },
  color: {
    color: '#333232',
  },
  orderStatus: {
    fontSize: px2dp(28),
  },
  // user: {
  //   flexDirection: 'row',
  //   alignItems: 'center',
  //   justifyContent: 'space-between',
  //   marginTop: px2dp(24),
  // },
  price: {
    fontSize: px2dp(20) * 2,
    color: '#333232',
  },
  // color: {
  //   color: '#333232'
  // },
});
